<?php
/**
 * Controller is the customized base controller class.
 * All controller classes for this application should extend from this base class.
 */
class BaseController extends CController
{
    public $layout;
    public $baseUrl;

    public function init()
    {
        $this->layout = '/layouts/main';
        $this->baseUrl = Yii::app()->getBaseUrl(true);
    }

    protected function beforeAction($action)
    {
        // check login
        $curPage = Yii::app()->controller->id.'/'.Yii::app()->controller->action->id;
        $isLogin = FacebookUtility::getUserId();
        if($curPage != CONST_LOGIN_PAGE && !$isLogin)
        {
            $this->redirect((array)CONST_LOGIN_PAGE);
        }
        elseif($curPage == CONST_LOGIN_PAGE && $isLogin)
        {
            $this->redirect((array)CONST_LOGIN_REDIRECT);
        }

        // set locale from cookie
        $request = Yii::app()->request;
        if(isset($request->cookies[ENUM_COOKIE_LANGUAGE]))
        {
            Yii::app()->language = $request->cookies[ENUM_COOKIE_LANGUAGE]->value;
        }

        return parent::beforeAction($action);
    }

    protected function afterRender($view, &$output)
    {
        // facebook init
        $js = 'FB.Event.subscribe("auth.login",function(){window.location="%s";});';
        $js = sprintf($js, $this->createUrl(CONST_LOGIN_SUCCESS));
        $facebook = Yii::app()->facebook;
        $facebook->addJsCallback($js);
        $facebook->initJs($output);
        $facebook->renderOGMetaTags();

        return parent::afterRender($view,$output);
    }

    public function render($view, $data = null, $js = null, $css = null, $return = false)
    {
        // default script
        Yii::app()->clientScript->registerCssFile(CONST_GOOGLE_FONT_OPEN_SANS);
        AssetUtility::addJs('libs/jquery-1.10.2.min.js');
        AssetUtility::addJs('libs/underscore-1.5.2-min.js');

        // layout
        AssetUtility::addCss($this->layout.'.css');
        AssetUtility::addJs($this->layout.'.js');

        // autoload
        $controller = StringUtility::toUnderscore(Yii::app()->controller->id);
        AssetUtility::addCss('views/'.$controller.'/'.$view.'.css');
        AssetUtility::addJs('views/'.$controller.'/'.$view.'.js');

        // js
        if(is_array($js))
        {
            foreach($js as $file)
            {
                AssetUtility::addJs($file);
            }
        }

        // css
        if(is_array($css))
        {
            foreach($css as $file)
            {
                AssetUtility::addCss($file);
            }
        }

        return parent::render($view, $data, $return);
    }
}